package com.sinbad.fileupload.controller;


import com.sinbad.common.core.util.DateUtils;
import com.sinbad.fileupload.config.MinioTemplate;
import com.sinbad.fileupload.entity.MinioConfig;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * minio上传,下载,删除接口
 */
@RestController
@RequestMapping("/minio")
public class MinioController {


    @Autowired
    private MinioTemplate minioTemplate;

    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioClient client;


    @ApiOperation(value = "创建桶")
    @PostMapping(value = "/createBucket")
    public String createBucket(String bucketName) {
        minioTemplate.createBucket(bucketName);
        return "sucess";
    }


    /**
     * 上传文件
     *
     * @param file
     * @return
     * @throws Exception Exception
     */
    @ApiOperation(value = "上传文件")
    @PostMapping(value = "/upload")
    @SneakyThrows(Exception.class)
    public String upload(@RequestParam("file") MultipartFile file) throws Exception {
        return uploadFile(file);
    }


    /**
     * 文件上传
     *
     * @param file
     * @return
     * @throws Exception
     */
    private String uploadFile(MultipartFile file) throws Exception {
        /* String fileName = FileUploadUtil.extractFilename(file);*/
        String fileName = file.getOriginalFilename();
        fileName = DateUtils.datePath() + "/" + fileName;
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(minioConfig.getBucketName())
                .object(fileName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
        client.putObject(args);
        return minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + fileName;
    }


}
